<?php
class fwLoginYahoo
{
	private static $appId = null;
	private static $secret = null;

	private static $loaded = false;

	private static function initVars()
	{
		global $conf;

		if(self::$loaded)
		{
			return;
		}

		self::$appId = $conf['login']['yahoo']['appid'];
		self::$secret = $conf['login']['yahoo']['secret'];

		self::$loaded = true;
	}

	public static function getLoginUrl($context=null)
	{
		self::initVars();

		$part_url = '/WSLogin/V1/wslogin?appid='.self::$appId.'&send_userhash=1&ts='. time();
		if($context!==null)
		{
			$part_url .= '&appdata='.$context;
		}
		$sig = md5($part_url.self::$secret);
		$url = 'https://api.login.yahoo.com'.$part_url.'&sig='.$sig;

		return $url;
	}

	public static function getLogoutUrl()
	{
		self::initVars();

		return 'http://login.live.com/logout.srf?appid=' . self::$appId;
	}

	public function processLogin($datas)
	{
		self::initVars();

		$ts  = $datas["ts"];    // the current unix time
		$sig = $datas["sig"];   // the signature of the request
		$user = $datas['userhash'];   // the signature of the request

		return self::processToken($ts, $sig, $user);
	}

	private function processToken($ts, $sig, $user)
	{
		$relative_url = getenv( 'REQUEST_URI' );
		$match = array();

		// The signature is a 32 character hex string, and is the last
		// parameter at the end of the request.
		$match_rv = preg_match(  "/^(.+)&sig=(\w{32})$/", $relative_url, $match);

		if ( $match_rv == 1 )
		{
			if ($match[2] != $sig )
			{
				return array(false, 'Duplicate sig parameters passed?: '.$sig.', ' . $match[2]);
			}
		}
		else
		{
			return array(false, 'Missing or invalid sig parameter');
		}
		// at this point, the url looks valid, and the sig was parsed from the url
		$relative_url_without_sig = $match[1];

		// Check that the ts parameter is within 600 seconds of the current time
		$current_time = time();
		$clock_skew  = abs($current_time - $ts);
		if ( $clock_skew >= 600 )
		{
			return array(false, 'invalid timestamp: clock_skew is '.$clock_skew .'seconds');
		}

		// now calculate the signature, and verify that the resulting signature
		// equals what was passed to us
		$sig_input = $relative_url_without_sig . self::$secret;
		$calculated_sig = md5($sig_input);
		if ( $calculated_sig == $sig )
		{
			return array(true, $user, true);
		}
		else
		{
			return array(false, 'calculated_sig '.$calculated_sig.' does not match sig parameter '.$sig);
		}
	}
}
?>